import axios from 'axios';
import Cookies from 'js-cookie';
import utils from './utils.js';
import {webHost, clientID, tokenUri,initDictionaryList } from './api';

export const funAxios = function (method,url,param,contentType,async){
    // 初始化字典
    if(!sessionStorage.allDictData||sessionStorage.allDictData=='[]'||sessionStorage.allDictData=='undefined'||utils.isEmpty(sessionStorage.allDictData)||utils.isEmpty(JSON.parse(sessionStorage.allDictData))){
        let params2 = {
            data:{isPageAble: false},
            access_token:"?access_token="+localStorage.token
        }
        initDictionaryList(params2).then(res=>{
            sessionStorage.allDictData = JSON.stringify(res.data.data.list) ;
        }).catch(err=>{
            console.log(err);
        });
    }
    var reqParamuilder = {url:url+"?access_token="+localStorage.token
        ,method:method
        ,data:param
        ,headers: {'Authorization': 'Bearer '+localStorage.token,'token':localStorage.token}}
    if(contentType&&contentType.length>5){
        reqParamuilder.dataType=contentType;
    }
    // console.log("------------------------------------- "+localStorage.token)
    if(async==false){
        // todo 请勿使用同步请求
        $.ajax({ url: reqParamuilder.url, context: reqParamuilder.data, success: function(res){
                console.log(" 功能未完成，请无勿使用同步请求 ?????????????????????????????? ");
                // console.log(res);
            }});
    }else {
        return axios(reqParamuilder).then(function(res){
            if (res && res.status=='200' ) {
                //如果token，基本那么就返回200：
                // console.log(res);
                if(res.data.code=="SZUUL100506"){// 服务未连接, 请稍后再试
                    console.log("服务未连接, 请稍后再试 todo ");
                    goLoginPage();
                }
                return res;
            }
        }).catch(err=>{
            if (err && err.response && err.response.status ) {
                console.log(err)
                console.log(err.response)
                console.log(err.response.data)
                console.log(err.response.status)
                console.log("尝试刷新token");
                if(err.response.status>=400&&err.response.status<=499 && err.response.status!=404 /*&& err.response.data.error == "invalid_token"*/){
                    // 尝试刷新token 失败后跳登录页面
                    reTryNum=0;
                    return goReFershToken(method,url,param,contentType);
                }else{
                    throwUnknownERR(err,"系统异常：");
                }
            }else if(err.message){
                console.log("网络错误：");
                console.log(err.message)
                console.log(err)
                reTryNum=0;
                return goReFershToken(method,url,param,contentType);
            }else{
                throwUnknownERR(err,"错误对象异常！");
            }
        });
    }
}



function goReFershToken(method,url,param,contentType) {
    return axios({
        url:tokenUri
        ,method:"POST"
        ,data:"grant_type=refresh_token&refresh_token="+localStorage.retoken
        ,headers: {'Authorization': 'Basic '+clientID,"Content-Type":"application/x-www-form-urlencoded"}// 'dGVzdDI6dGVzdDI=' test2:test2 ||  'd2ViOndlYg==' web:web
    }).then(function(res){
        if(res && res.status=='200'){
            localStorage.token = res.data.access_token
            localStorage.retoken = res.data.refresh_token
            // console.log("刷新token成功，回调接口：method:"+method+" url:"+url+" param"+param);
            return funAxios(method,url,param,contentType);// 成功后回调原来的请求
        }else{ console.log("刷新token失败，但是没抛异常：");console.log(res);throw '请重新登录4';  }
    }).catch(err=>{// 有可能 retoken 过期，或者参数有误缺失
        console.log("刷新token失败");
        console.log(err.response.data)
        console.log(err);
        if((err.response.data&&err.response.status>=400&&err.response.status<=499&&err.response.status!=404)){
            goLoginPage();
        }else if(err.response.data&&err.response.status==500/*&&err.response.data.error_description&&err.response.data.error_description.indexOf("Jedis") != -1*/){//  redis access 数据被删除
            console.log(" 500 状态码，尝试重试 "+reTryNum)
            return reTryFershToken(method,url,param,contentType)
        }else{throwUnknownERR(err);}
    });
}

var reTryNum = 0;
var maxTryNum = 2
function reTryFershToken(method,url,param,contentType) {
    if(reTryNum<(maxTryNum-1)){
        reTryNum++;
        return goReFershToken(method,url,param,contentType);
    }else{
        reTryNum=0;
        goLoginPage();
    }
}

function goLoginPage() {
    console.log("跳转到重新登录页面");
    Cookies.remove('user');
    Cookies.remove('password');
    Cookies.remove('access');
    window.location.href=webHost+"/#/login";
}

function throwUnknownERR(err,msg) {
    if(!msg){msg="未知状态："}
    try{
        console.log(msg+""+err.response.status)
        console.log(err.response.data)
        console.log(err);
    }catch(err) {}
    throw err;
}
